package com.moyun.zbmy.zizhou.ui.fragment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Cache;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.base.BaseAccountActivity;
import com.moyun.zbmy.zizhou.beans.AccountNewsItem;
import com.moyun.zbmy.zizhou.beans.AccountNewsVo;
import com.moyun.zbmy.zizhou.beans.AccountNodeBean;
import com.moyun.zbmy.zizhou.beans.FRebellion;
import com.moyun.zbmy.zizhou.beans.HomeListItem;
import com.moyun.zbmy.zizhou.beans.NewsItem;
import com.moyun.zbmy.zizhou.beans.SingleResult;
import com.moyun.zbmy.zizhou.beans.Titles;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.http.ParamsEditor;
import com.moyun.zbmy.zizhou.ui.activities.AccountKnockOutDetailActivity;
import com.moyun.zbmy.zizhou.ui.activities.AccountNewsDetailActivity;
import com.moyun.zbmy.zizhou.ui.activities.AccountSearchNewsActivity;
import com.moyun.zbmy.zizhou.ui.activities.MoreAccountActivity;
import com.moyun.zbmy.zizhou.ui.activities.MyAttentionActivity;
import com.moyun.zbmy.zizhou.ui.adapter.AttentionAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.holder.ApplyHolder;
import com.moyun.zbmy.zizhou.ui.adapter.holder.AttentionEntryHolder;
import com.moyun.zbmy.zizhou.ui.adapter.holder.AttentionMoreImgNewsHolder;
import com.moyun.zbmy.zizhou.ui.adapter.holder.AttentionNewsHolder;
import com.moyun.zbmy.zizhou.ui.adapter.holder.BaseAbsHolder;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.utils.UserManager;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;
import static com.moyun.zbmy.zizhou.ui.fragment.ApplyFragment.CODE_REQUEST_LOGIN;

/**
 * 互动
 */
public class AttentionFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, AttentionAdapter.OnAttentionNewsClickListener, AttentionEntryHolder.OnAttentionEntryClickListener {
    @BindView(R.id.common_frg_refreshlayout)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;
    private AttentionAdapter mAdapter;
    protected static final int CODE_REQUEST_LOGIN = 111;
    protected static final int CODE_REQUEST_DETAIL = 112;
    private boolean isGetAttention = false;
    private int mPageNo = 0;
    private boolean mIsLoading = false;
    private int mPageAll = 0;
    private HomeListItem entry = new HomeListItem();
    private List<IListShowData> dataList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_attention, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRefreshLayout.setLoadMoreEnabled(false);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRefreshLayout.autoRefresh();
        getNodeInfo();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onLoadMore() {
        mPageNo++;
        if (isGetAttention) {
            getAttentionNewsData();
        } else {
            getRecommendNewsData();
        }
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        dataList.clear();
        entry.setViewType(AttentionAdapter.VIEWTYPE_ATTENTION_IN);
        dataList.add(entry);
        mPageNo = 0;
        mIsLoading = true;
        getAttentionNewsData();
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    private void getAttentionNewsData() {
        if (null != UserManager.getInstance().getUser()) {
            String token = UserManager.getInstance().getUser().getToken();
            String userId = UserManager.getInstance().getUser().getUserId();
            Map<String, Object> param = new HashMap<>();
            param.put("siteNumber", Constances.SITE_ID);
            param.put("userId", userId);
            param.put("token", token);
            param.put("index", "" + mPageNo);
            param.put("capacity", "10");
            NetUtils.getNetAdapter().getAttentionNewsList(getOwnerName(), param, new AbsNetCallBack<AccountNewsVo>(AccountNewsVo.class) {
                @Override
                public void onSuc(AccountNewsVo listVo) {
                    if (null != listVo && ListUtils.isListValued(listVo.getResultList())) {
                        mPageAll = listVo.getPageAll();
                        isGetAttention = true;
                        Titles title = new Titles();
                        title.setViewType(AttentionAdapter.VIEWTYPE_NEWS_TITLE_LINE);
                        dataList.add(title);
                        dataList.addAll(listVo.getResultList());
                    }
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    if (mPageNo >= 1) {
                        mPageNo--;
                    }
                }

                @Override
                public void onEnd() {
                    if (ListUtils.isListValued(dataList) && dataList.size() > 1) {
                        isGetAttention = true;
                        onNetFinish();
                        initData();
                    } else {
                        isGetAttention = false;
                        dataList.clear();
                        entry.setViewType(AttentionAdapter.VIEWTYPE_ATTENTION_IN);
                        dataList.add(entry);
                        mPageNo = 0;
                        getRecommendNewsData();
                    }
                }
            });
        } else {
            isGetAttention = false;
            dataList.clear();
            entry.setViewType(AttentionAdapter.VIEWTYPE_ATTENTION_IN);
            dataList.add(entry);
            mPageNo = 0;
            getRecommendNewsData();
        }

    }

    private void getRecommendNewsData() {
        String token = "";
        String userId = "";
        if (null != UserManager.getInstance().getUser()) {
            token = UserManager.getInstance().getUser().getToken();
            userId = UserManager.getInstance().getUser().getUserId();
        }
        Map<String, Object> param = new HashMap<>();
        param.put("siteNumber", Constances.SITE_ID);
        param.put("userId", userId);
        param.put("token", token);
        param.put("index", "" + mPageNo);
        param.put("capacity", "10");
        param.put("type", 2);
        NetUtils.getNetAdapter().getRecommendAttentionNewsList(getOwnerName(), param, new AbsListNetCallback<AccountNewsItem>(null) {
            @Override
            public void onSuc(List<AccountNewsItem> newsList) {
                if (ListUtils.isListValued(newsList)) {
                    for (int i = 0; i < newsList.size(); i++) {
                        newsList.get(i).setShowAttention(true);
                    }
                    Titles title = new Titles();
                    title.setViewType(AttentionAdapter.VIEWTYPE_NEWS_TITLE);
                    title.setTitle("大家都在关注");
                    dataList.add(title);
                    dataList.addAll(newsList);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {

            }

            @Override
            public void onEnd() {
                onNetFinish();
                initData();
            }
        });

    }

    /**
     * 获取互动栏目的 nodeId
     */
    private void getNodeInfo() {
        NetUtils.getNetAdapter().getFollowedNodeListList(getOwnerName(), "sctv/anchor/index/anchor.json", new AbsListNetCallback<AccountNodeBean>(null) {
            @Override
            public void onSuc(List<AccountNodeBean> nodeList) {
                if (ListUtils.isListValued(nodeList)) {
                    for (int i = 0; i < nodeList.size(); i++) {
                        if (nodeList.get(i).getFollowedNodeFlag().equalsIgnoreCase("anchor_node")) {
                            Cache.getInstance().setAccountNodeId("" + nodeList.get(i).getFollowedNodeId());
                            break;
                        }
                    }

                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {

            }

            @Override
            public void onEnd() {
//                onNetFinish();
            }
        });
    }

    private void initData() {
        if (mAdapter == null) {
            mAdapter = new AttentionAdapter(getActivity(), dataList, this, this);
            mRecyclerView.setAdapter(mAdapter);
            mAdapter.setShowAuthor(true);
        } else {
            mAdapter.setData(dataList);
        }
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();
        if (isGetAttention) {
            mRefreshLayout.setLoadMoreEnabled(mPageNo + 1 >= mPageAll ? false : true);
        } else {
            mRefreshLayout.setLoadMoreEnabled(false);
        }
    }

    @Override
    public void OnItemClick(AccountNewsItem temp, int type) {
        if (type == AttentionAdapter.VIEWTYPE_NEWS_ITEM) {
            Intent intent = new Intent(getActivity(), AccountNewsDetailActivity.class);
            intent.putExtra(AccountNewsDetailActivity.NEWS_BEAN, temp);
            getActivity().startActivityForResult(intent, CODE_REQUEST_DETAIL);
        } else if (type == AttentionAdapter.VIEWTYPE_NEWS_IMG_ITEM) {
            Intent intent = new Intent(getActivity(), AccountKnockOutDetailActivity.class);
            intent.putExtra(AccountKnockOutDetailActivity.NEWS_BEAN, temp);
            getActivity().startActivityForResult(intent, CODE_REQUEST_DETAIL);
        }
    }

    @Override
    public void OnItemAccountClick(AccountNewsItem temp) {
        //TODO 进入互动账号详情
    }

    @Override
    public void OnItemCommentClick(AccountNewsItem temp, int position) {
        //TODO 新闻评论
    }

    @Override
    public void OnItemDiggClick(AccountNewsItem temp, int position) {
        //TODO 新闻点赞
        if (null != UserManager.getInstance().getUser()) {
            doUp(temp, position);
        } else {
            toLogin();
        }
    }

    @Override
    public void OnItemAttentionClick(AccountNewsItem temp, int position) {
        //TODO 去关注
        if (UserManager.getInstance().isLogin()) {
            toAttentionClick(temp);
        } else {
            toLogin();
        }
    }

    @Override
    public void OnEntryClick(int clickPosition) {
        if (clickPosition == 1) {
            //TODO 我的关注
            if (null != UserManager.getInstance().getUser()) {
                Intent intent = new Intent(getContext(), MyAttentionActivity.class);
                startActivity(intent);
            } else {
                toLogin();
            }
        } else if (clickPosition == 2) {
            //TODO 更多关注
//            if (null != UserManager.getInstance().getUser()) {
            Intent intent = new Intent(getContext(), MoreAccountActivity.class);
            startActivity(intent);
//            } else {
//                toLogin();
//            }
        }
    }

    @OnClick({R.id.input_key})
    protected void OnClick(View v) {
        if (v.getId() == R.id.input_key) {
            Intent intent = new Intent(getContext(), AccountSearchNewsActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CODE_REQUEST_LOGIN || requestCode == CODE_REQUEST_DETAIL) {
                mRefreshLayout.autoRefresh();
            }
        }
    }

    /**
     * 处理 关注或取消关注
     *
     * @param bean
     */
    private void toAttentionClick(final AccountNewsItem bean) {
        if (bean.getFollowedStatus() == 1) {
            toUnAttentionAccount("" + bean.getFollowedId(), new BaseAccountActivity.OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {

                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {
                    for (int i = 0; i < dataList.size(); i++) {
                        if (dataList.get(i) instanceof AccountNewsItem && ((AccountNewsItem) dataList.get(i)).getNewsDetailId() == bean.getNewsDetailId()) {
                            ((AccountNewsItem) dataList.get(i)).setFollowedStatus(0);
                            mAdapter.setData(dataList);
                            break;
                        }
                    }
                }
            });
        } else {
            toAttentionAccount("" + bean.getFollowedId(), new BaseAccountActivity.OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {
                    for (int i = 0; i < dataList.size(); i++) {
                        if (dataList.get(i) instanceof AccountNewsItem && ((AccountNewsItem) dataList.get(i)).getNewsDetailId() == bean.getNewsDetailId()) {
                            ((AccountNewsItem) dataList.get(i)).setFollowedStatus(1);
                            mAdapter.setData(dataList);
                            break;
                        }
                    }
                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {

                }
            });
        }
    }

    public void toAttentionAccount(String accountId, final BaseAccountActivity.OnAttentionListener listener) {
        if (null != UserManager.getInstance().getUser()) {
            String token = UserManager.getInstance().getUser().getToken();
            String userId = UserManager.getInstance().getUser().getUserId();
            Map<String, Object> param = new HashMap<>();
            param.put("siteNumber", Constances.SITE_ID);
            param.put("token", token);
            param.put("userId", userId);
            param.put("followedId", accountId);

            NetUtils.getNetAdapter().addAttentionAccount(getOwnerName(), param, new AbsNetCallBack<String>(String.class) {
                @Override
                public void onSuc(String result) {
                    if (null != listener) {
                        toast("关注成功");
                        listener.OnAttention(true, 0);
                    }
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
//                    toast(errorMsg);
                    if (null != listener) {
                        toast("关注失败");
//                        listener.OnAttention(false, 0);
                    }
                }

                @Override
                public void onEnd() {
                    super.onEnd();
                }
            });
        }


    }

    public void toUnAttentionAccount(String accountId, final BaseAccountActivity.OnAttentionListener listener) {
        if (null != UserManager.getInstance().getUser()) {
            String token = UserManager.getInstance().getUser().getToken();
            String userId = UserManager.getInstance().getUser().getUserId();
            Map<String, Object> param = new HashMap<>();
            param.put("siteNumber", Constances.SITE_ID);
            param.put("token", token);
            param.put("userId", userId);
            param.put("followedId", accountId);

            NetUtils.getNetAdapter().deleteAttentionAccount(getOwnerName(), param, new AbsNetCallBack<String>(String.class) {
                @Override
                public void onSuc(String result) {
                    if (null != listener) {
                        toast("取消关注成功");
                        listener.OnUnAttention(true, 0);

                    }
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
//                    toast(errorMsg);
                    if (null != listener) {
                        toast("取消关注失败");
//                        listener.OnUnAttention(false, 0);
                    }
                }

                @Override
                public void onEnd() {
                    super.onEnd();
                }
            });
        }

    }

    private BaseAbsHolder diggHolder = null;

    private void doUp(final AccountNewsItem temp, final int position) {
//        Map<String, Object> param = new HashMap<>();
//        param.put("dynamicId", temp.getNewsDetailId());
//        param.put("userId", UserManager.getInstance().getUser().getUserId());
//        param.put("token",  UserManager.getInstance().getUser().getToken());
//        param.put("fType", 3);
        ParamsEditor pe = new ParamsEditor();
        pe.put("dynamicId", temp.getNewsDetailId());
        pe.put("fType", 3);//1 主播 2报料 3新闻 4 直播 5视频
        pe.put("userId", UserManager.getInstance().getUser().getUserId());

        RecyclerView.LayoutManager manager = mRecyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(position);

        if (null != lastView) {
            if (mRecyclerView.getChildViewHolder(lastView) instanceof AttentionNewsHolder) {
                diggHolder = (AttentionNewsHolder) mRecyclerView.getChildViewHolder(lastView);
                if (null != diggHolder) {
                    ((AttentionNewsHolder) diggHolder).getAttentionNewsDigg().setDrawableEnlarge();
                }
            } else if (mRecyclerView.getChildViewHolder(lastView) instanceof AttentionMoreImgNewsHolder) {
                diggHolder = (AttentionMoreImgNewsHolder) mRecyclerView.getChildViewHolder(lastView);
                if (null != diggHolder) {
                    ((AttentionMoreImgNewsHolder) diggHolder).getAttentionNewsDigg().setDrawableEnlarge();
                }
            }
        }

        NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onSuc(SingleResult singleResult) {
                if (singleResult.isSuccess() && null != diggHolder) {
                    CustomFontTextView diggView = null;
                    if (diggHolder instanceof AttentionNewsHolder) {
                        diggView = ((AttentionNewsHolder) diggHolder).getAttentionNewsDigg();
                    } else if (diggHolder instanceof AttentionMoreImgNewsHolder) {
                        diggView = ((AttentionMoreImgNewsHolder) diggHolder).getAttentionNewsDigg();
                    }
                    if (null != diggView && mAdapter.getItem(position) instanceof AccountNewsItem) {
                        AccountNewsItem newsItem = (AccountNewsItem) mAdapter.getItem(position);

                        if (newsItem.isNewsDetailAttitudesStatus()) {
                            newsItem.setNewsDetailAttitudesStatus(false);
                            newsItem.setNewsDetailAttitudesCount(newsItem.getNewsDetailAttitudesCount() - 1);

                            Drawable drawable = getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                            diggView.setDrawables(drawable, null, null, null);
                            diggView.setTextColor(getResources().getColor(R.color.colorOpinionSelectNo));
                            if (UserManager.isLoginS()) {
                                StatisticsMainInit.thumbsUpLog(UserManager.getInstance().getUser().getPhoneNumber(),String.valueOf(temp.getNewsDetailId()),
                                        temp.getNewsDetailTitle(),2);
                            }else{
                                StatisticsMainInit.thumbsUpLog("", String.valueOf(temp.getNewsDetailId()),
                                        temp.getNewsDetailTitle(),2);
                            }
                        } else {
                            newsItem.setNewsDetailAttitudesStatus(true);
                            newsItem.setNewsDetailAttitudesCount(newsItem.getNewsDetailAttitudesCount() + 1);

                            Drawable drawable = getResources().getDrawable(R.mipmap.icon_compere_btn_press);
                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                            diggView.setDrawables(drawable, null, null, null);
                            diggView.setTextColor(getResources().getColor(R.color.colorTxRedMain_));
                            addInvitation(Constances.ADD_INTEGRAL_DOUP);
                            if (UserManager.isLoginS()) {
                                StatisticsMainInit.thumbsUpLog(UserManager.getInstance().getUser().getPhoneNumber(),String.valueOf(temp.getNewsDetailId()),
                                        temp.getNewsDetailTitle(),1);
                            }else{
                                StatisticsMainInit.thumbsUpLog("", String.valueOf(temp.getNewsDetailId()),
                                        temp.getNewsDetailTitle(),1);
                            }
                        }

                        long upCount = newsItem.getNewsDetailAttitudesCount();
                        if (upCount > 0) {
                            diggView.setText(String.valueOf(upCount));
                        } else {
                            diggView.setText("点赞");
                        }
                    }
                }


            }
        });
    }

}
